package com.sduept.nwld.dataserver.util;

import com.sduept.cim.model.core.Substation;
import com.sduept.cim.model.extend.LineTower;
import com.sduept.generator.ObjectId;
import com.sduept.bigdata.document.core.CommonDocumentProperties;
import com.sduept.utils.SpringContext;
import com.sduept.utils.ZipUtil;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ExportFileUtil {
	private static String tmpDownloadPath="";
	private static final String linux_separator = "/";
	private static List<String> selectedDefectField=new ArrayList<String>();
	private static Map<String,String> header_field_map=new HashMap<String,String>();
	private static CommonDocumentProperties pros = SpringContext.getBean(CommonDocumentProperties.class);
	public static StreamedContent exportLineInfoToCSV(Map<String,List<Object>> lts_result,StreamedContent file){    	
		try {
			if(lts_result!=null && !lts_result.isEmpty()){
				String tmpDownload = ObjectId.get().toString();
				String tmpDownloadDir = pros.getExportTempPath() +linux_separator+ tmpDownload;
				String exportDir=pros.getExportTempPath();
				tmpDownloadPath= tmpDownloadDir+".zip";
				List<File> list = new ArrayList<File>();
				selectedDefectField.add("线路Id");
				selectedDefectField.add("线路名称");
				selectedDefectField.add("lineString");
				header_field_map.put("线路Id","lineId");
				header_field_map.put("线路名称","linename");
				header_field_map.put("lineString","lineString");
				for(String fileName:lts_result.keySet()){
					List<ExportLineInfoModel> infos =genExportInfo(lts_result.get(fileName));
					ExcelUtil eu= new ExcelUtil();
					eu.exportExcel(selectedDefectField, header_field_map, infos,exportDir+fileName+".csv",fileName);
					copyFile(exportDir+fileName+".csv",tmpDownloadDir+linux_separator+fileName+".csv");
				}				
				list.add(new File(tmpDownloadDir));
				ZipUtil.zipFile(tmpDownloadPath, list);
		    	ZipUtil.deletefile(tmpDownloadDir);
		    	for(String fileName:lts_result.keySet()){
		    		ZipUtil.deletefile(exportDir+fileName+".csv");
		    	}
				InputStream stream;
				try {
					stream = new FileInputStream(new File(pros.getExportTempPath()+tmpDownload+".zip"));
					file = new DefaultStreamedContent(stream, "application/octet-stream",tmpDownload+".zip");
			    	new DeleteThread(tmpDownloadPath).start();
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
			}else{
				return file;
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}finally{
			selectedDefectField.clear();
			header_field_map.clear();
		}
		return file;
	}
	
	
	private static List<ExportLineInfoModel> genExportInfo(List<Object> list) {
		List<ExportLineInfoModel> exportLineInfoModels=new ArrayList<ExportLineInfoModel>();
		if(list!=null && !list.isEmpty()){
			for(Object obj:list){
				ExportLineInfoModel exportLineInfoModel=new ExportLineInfoModel();
				if(obj instanceof LineTower){
					exportLineInfoModel.setLineId(((LineTower) obj).getLineId());
					exportLineInfoModel.setLineName(((LineTower) obj).getLineName());
					StringBuilder sb = new StringBuilder();
					sb.append("LINESTRING (");
					int i = 0;
					for(Object obj2:list){
						if(obj2 instanceof LineTower){
							if(i == 0)
								sb.append(((LineTower) obj2).getLongitude()+" "+((LineTower) obj2).getLatitude());
							else
								sb.append(", "+((LineTower) obj2).getLongitude()+" "+((LineTower) obj2).getLatitude());
							i++;
						}
					}
					sb.append(")");
					exportLineInfoModel.setLineString(sb.toString());		
					exportLineInfoModels.add(exportLineInfoModel);
				}
			}
		}
		return exportLineInfoModels;
	}


	public static StreamedContent  exportTowerInfoToCSV( Map<String, List<LineTower>> tower_result,StreamedContent file){
		try {
			if(tower_result!=null && !tower_result.isEmpty()){
				String tmpDownload = ObjectId.get().toString();
				String tmpDownloadDir = pros.getExportTempPath() +linux_separator+ tmpDownload;
				String exportDir=pros.getExportTempPath();
				tmpDownloadPath= tmpDownloadDir+".zip";
				List<File> list = new ArrayList<File>();
				selectedDefectField.add("线路名称");
				selectedDefectField.add("线路号");
				selectedDefectField.add("电压等级");
				selectedDefectField.add("杆塔号");			
				selectedDefectField.add("整体线路顺序号");		
				selectedDefectField.add("经度");
				selectedDefectField.add("纬度");
				selectedDefectField.add("距离起始变电站(米)");
				selectedDefectField.add("距离上一杆塔(米)");
				header_field_map.put("杆塔号","towerno");
				header_field_map.put("整体线路顺序号","serialno");
				header_field_map.put("经度","longitude");
				header_field_map.put("纬度","latitude");
				header_field_map.put("线路号","lineno");
				header_field_map.put("线路名称","linename");
				header_field_map.put("电压等级","lineVoltage");
				header_field_map.put("距离起始变电站(米)","distanceFromStartStation");
				header_field_map.put("距离上一杆塔(米)","distanceFromLastTower");
				for(String fileName:tower_result.keySet()){
					ExcelUtil eu= new ExcelUtil();
					eu.exportExcel(selectedDefectField, header_field_map, tower_result.get(fileName),exportDir+fileName+".csv",fileName);
					copyFile(exportDir+fileName+".csv",tmpDownloadDir+linux_separator+fileName+".csv");
				}
				list.add(new File(tmpDownloadDir));
				ZipUtil.zipFile(tmpDownloadPath, list);
		    	ZipUtil.deletefile(tmpDownloadDir);
		    	for(String fileName:tower_result.keySet()){
		    		ZipUtil.deletefile(exportDir+fileName+".csv");
		    	}
				InputStream stream;
				try {
					stream = new FileInputStream(new File(pros.getExportTempPath()+tmpDownload+".zip"));
					file = new DefaultStreamedContent(stream, "application/octet-stream",tmpDownload+".zip");
			    	new DeleteThread(tmpDownloadPath).start();
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
			}else{
				return file;
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}finally{
			selectedDefectField.clear();
			header_field_map.clear();
		}
		return file;
	}
	
	public static StreamedContent exportStationInfoToCSV( List<Substation> tower_result,StreamedContent file){
		try {
			if(tower_result!=null && !tower_result.isEmpty()){
				String fileName="cimSubstation";
				String tmpDownload = ObjectId.get().toString();
				String tmpDownloadDir = pros.getExportTempPath() +linux_separator+ tmpDownload;
				String exportDir=pros.getExportTempPath();
				tmpDownloadPath= tmpDownloadDir+".zip";
				List<File> list = new ArrayList<File>();
				selectedDefectField.add("id");			
				selectedDefectField.add("pasId");
				selectedDefectField.add("变电站名");
				selectedDefectField.add("经度");
				selectedDefectField.add("纬度");
				selectedDefectField.add("电压等级");
				selectedDefectField.add("standVoltagelevel");		
				selectedDefectField.add("actualVoltage");
				header_field_map.put("id","id");
				header_field_map.put("pasId","pasId");
				header_field_map.put("变电站名","name");
				header_field_map.put("经度","longitude");
				header_field_map.put("纬度","latitude");
				header_field_map.put("电压等级","voltageLevel");
				header_field_map.put("standVoltagelevel","standVoltagelevel");
				header_field_map.put("actualVoltage","actualVoltage");
				ExcelUtil eu= new ExcelUtil();
				eu.exportExcel(selectedDefectField, header_field_map, tower_result,exportDir+fileName+".csv",fileName);
				copyFile(exportDir+fileName+".csv",tmpDownloadDir+linux_separator+fileName+".csv");
				list.add(new File(tmpDownloadDir));
				ZipUtil.zipFile(tmpDownloadPath, list);
		    	ZipUtil.deletefile(tmpDownloadDir);
		    	ZipUtil.deletefile(exportDir+fileName+".csv");
				InputStream stream;
				try {
					stream = new FileInputStream(new File(pros.getExportTempPath()+tmpDownload+".zip"));
					file = new DefaultStreamedContent(stream, "application/octet-stream",tmpDownload+".zip");
			    	new DeleteThread(tmpDownloadPath).start();
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
			}else{
				return file;
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}finally{
			selectedDefectField.clear();
			header_field_map.clear();
		}
		return file;
	}
	
	
	private static void copyFile(String source1,String target1){  
		File source=new File(source1);  
        File target=new File(target1);  
        FileInputStream fis=null;  
        FileOutputStream fos=null;  
        BufferedInputStream bis=null;  
        BufferedOutputStream bos=null;  
        byte[] ch=new byte[1024*1024];  
        int len=0;  
        try {  
            //创建流对象  
            fis=new FileInputStream(source);  
            //创建缓冲流  
            bis=new BufferedInputStream(fis);  
            if(!target.exists()){ 
                target.getParentFile().mkdirs();  
                target.createNewFile();
            }             
            fos=new FileOutputStream(new File(target1));  
            bos=new BufferedOutputStream(fos);  
            while((len=bis.read(ch))!=-1){  
                bos.write(ch,0,len);  
            }  
            //刷新缓冲区  
            bos.flush();  
              
        } catch (IOException e) {  
            e.printStackTrace();  
        }finally{  
       	 try {
				fis.close();
				 bis.close();
	        	 fos.close();
	        	 bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
        }  
   } 
	
	
	private static class DeleteThread extends Thread{
		String tempPath="";
		DeleteThread(String tempPath){
			this.tempPath = tempPath;
		}
		@Override
		public void run() {
			boolean flag=true;
			while(flag){
				File f = new File(tempPath);
				if(f.exists()){
					f.delete();
				}else{
					flag=false;
				}
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}


	public static String getTmpDownloadPath() {
		return tmpDownloadPath;
	}


	public static void setTmpDownloadPath(String tmpDownloadPath) {
		ExportFileUtil.tmpDownloadPath = tmpDownloadPath;
	}


	public List<String> getSelectedDefectField() {
		return selectedDefectField;
	}

	public Map<String, String> getHeader_field_map() {
		return header_field_map;
	}
	
}
